package search;

import java.util.ArrayList;

public class WithinTextSearch extends Search {
	
	public WithinTextSearch(ArrayList<app.Essay> essays)
	{
		super(essays);
	}
	
	public ArrayList<WithinResult> search()
	{
		app.Essay essay = (app.Essay)essays.get(0);
		ArrayList<WithinResult> results = new ArrayList<WithinResult>();
		int i;
		
		String[] theseWords;
		int sentLen = 0, v23 = 0, words = 0;
		double avgSentLen = 0, avgV23 = 0;
		
		//Get the stats
		for(i=0;i<essay.sentences.size();i++){
			//Increment total number of words
			theseWords = essay.sentences.get(i).split(" ");
			words += theseWords.length;
			
			//Sum sentence length
			sentLen += theseWords.length;	
			
			//Average small vowely words
			v23 += getSmallWords(theseWords);
		}
		//Calculate Averages
		avgSentLen = sentLen / words;
		avgV23 = v23 / words;
		
		//Do the check
		for(i=0;i<essay.sentences.size();i++){
			v23 = 0; //reset
			theseWords = essay.sentences.get(i).split(" ");
			
			//Sentence Deviation
			double sentDev = avgSentLen - theseWords.length;
			
			//Small Vowely Word deviation
			v23 += getSmallWords(theseWords);
			double habitDev = avgV23 - v23;
			
			//Create result
			results.add(new WithinResult(i, essay.getSentence(i), true, sentDev, habitDev));
		}
		return results;
	}
	
	public int getSmallWords(String[] theseWords)
	{
		//Words with 2 or 3 letters and start with a vowel
		int v23 = 0;
		for(int i=0;i<theseWords.length;i++){
			String word = theseWords[i];
			char firstChar = word.charAt(0);
			if(firstChar == 'a' || firstChar == 'A' || 
			   firstChar == 'e' || firstChar == 'E' ||
			   firstChar == 'i' || firstChar == 'I' ||
			   firstChar == 'o' || firstChar == 'O' ||
			   firstChar == 'u' || firstChar == 'U')
				
				v23++;
				
			//if((firstChar.indexOf("AEIOU") > 0) || (firstChar.indexOf("aeiou") > 0))
				//v23++;
			else
				if((word.length() > 1) && (word.length() < 4))
					v23++;						
		}
		return v23;
	}
}
